/**
 * 任务消息指令监听器
 * 
 * @author  liupeng
 * 
 * @date 2017-02-06
 */
package com.zed.app.push.listener;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;

import com.zed.api.player.push.service.PlayerPushTaskApiService;
import com.zed.app.push.FcmPush;
import com.zed.app.push.handler.PushMessageHandler;
import com.zed.app.push.handler.PushMessageHandlerFactory;
import com.zed.common.ConstantType;
import com.zed.common.ConstantType.PushTaskTargetType;
import com.zed.common.task.context.TaskContext;
import com.zed.common.task.message.TaskMessage;
import com.zed.common.task.message.protobuf.TaskMessageListener;
import com.zed.common.util.JsonUtils;

public class PushCommondMessageListener extends TaskMessageListener {
	@Autowired
	private PushMessageHandlerFactory pushMessageHandlerFactory;
	@Autowired
	private PlayerPushTaskApiService playerPushTaskApiService;

	// 线池程
	@Resource(name = "taskExecutor")
	protected AsyncTaskExecutor taskExecutor;

	private  final Logger logger = Logger.getLogger(this.getClass());

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.zed.common.task.message.protobuf.TaskMessageListener#onMessage(com.
	 * zed.common.task.message.protobuf.TaskCommondMessage.Message)
	 */
	@Override
	public void onMessage(TaskMessage message) {
		PushMessageHandler task = pushMessageHandlerFactory.getHandler(message.getHead().getType());
		if (null == task) {
			logger.warn("找不到对应任务处理类  task type ->" + message.getHead().getType());
			return ;
		}
		if (logger.isInfoEnabled()) {
			logger.info("收到任务指令  ->" + message.toString());
		}
		TaskContext.entry().setTaskMessage(message);
		boolean success = false;
		try {
			task.doBiz();
			success = pushRemote();

		} catch (Exception ex) {
			logger.error("将消息推送到远程服务器出错", ex);
		} finally {
			try {
				// 修改目标发送状态
				int status = success ? ConstantType.PushTaskTargetStatusType.SUCCESS.getValue()
						: ConstantType.PushTaskTargetStatusType.FAIL.getValue();

				// 获取发送目标类型
				int targetType = Integer.parseInt(message.getAttribute("targetType").toString());
				if (targetType == PushTaskTargetType.APPOINT.getValue()) {
					// 修改发送目标状态
					playerPushTaskApiService.updateStatus(message.getAttribute("scheduleId").toString(),
							message.getAttribute("clientId").toString(), status);
				} else if (targetType == PushTaskTargetType.ONE_TOPIC.getValue() || targetType == PushTaskTargetType.MANY_TOPIC.getValue()) {
					playerPushTaskApiService.updateStatus(message.getAttribute("scheduleId").toString(),null, status);
				}
			} catch (Exception ex) {
				logger.error("修改目标发送状态失败", ex);
			}
			// 销毁任务上下文
			TaskContext.destory();
		}

	}

	/**
	 * 调用远推api
	 * 
	 * @return
	 * @throws Exception
	 */
	protected boolean pushRemote() throws Exception {
		TaskMessage message = TaskContext.entry().getTaskMessage();
		String title = message.hasAttribute("title") ? message.getAttribute("title").toString() : "";
		String icon=  message.hasAttribute("messageIcon") ? message.getAttribute("messageIcon").toString() : "";
		String body = message.getBody();
		int targetType = Integer.parseInt(message.getAttribute("targetType").toString());
		Map<String,String> result = null;
		if (targetType == PushTaskTargetType.APPOINT.getValue()) {
			 result = FcmPush.pushMsg(message.getHead().getType(),message.getAttributes(), message.getHead().getToId(), title, body,icon);
		}else if(targetType ==  PushTaskTargetType.ONE_TOPIC.getValue()){
			 result = FcmPush.pushMsg(message.getHead().getType(),message.getAttributes(), message.getHead().getToId(), title, body,icon,true,false);
		}else if(targetType ==  PushTaskTargetType.MANY_TOPIC.getValue()){
			 result = FcmPush.pushMsg(message.getHead().getType(),message.getAttributes(), message.getHead().getToId(), title, body,icon,true,true);
		}
			
		if (logger.isInfoEnabled()) {
			logger.debug("message push result  ---------->" + result);
		}
		try{
		String code = result.get("code");
		if (!"200".equals(code)) {
			logger.error("请求失败,http code->" + code);
		} else {
			Map<String, Object> response = JsonUtils.getMapByJsonStr(result.get("result"));
			if (targetType == PushTaskTargetType.APPOINT.getValue() && "1".equals(response.get("success").toString())) {
				return true;
			}else{
				return true;
			}
		}
		}catch(Exception ex){
			logger.error("push调用远程api响应 处理失败,result ->" + result,ex);
		}
		return false;

	}
}
